﻿/// <reference path="/@JSense.js" />
(function () {
    var BlackBirdApp = this.BlackBirdApp = (function ($) {

        //
        //class: requires:jQuery.history
        //
        var HistoryManager = {
            //
            //function:
            init: function () {
                HistoryManager.size = window.location.hash ? -1 : 0;
                $.history.init(HistoryManager.handleHash, { unescape: ",/&=?" });

                $('#main_area').delegate('.back_link', 'click', function () {
                    HistoryManager.back();
                });
            },

            //HistoryManager
            //function: called by history
            handleHash: function (hash) {
                var split, route, params = [];
                //                if (hash) {
                //                    split = hash.split('?');
                //                    route = split[0];
                //                    if (split.length > 1) {
                //                        $.each(split[1].split('&'), function (i, param) {
                //                            var parts = param.split('=');

                //                            params[parts[0]] = parts[1];
                //                        });
                //                    }
                //                };

                var location = window.location;
                route = location.pathname;

                split = route.split('/');
                if (split.length > 3) {
                    route = "/" + split[1] + "/" + split[2];
                }

                //route = location.pathname;

                switch (route) {
                    case '/Home/Index':
                        Views.ShowProjects(params);
                        break;
                    case "/BiJiaDan/CreateBiJiaDan":
                        Views.CreateBiJiaDan(params);
                        break;
                    case "/BiJiaDan/GetBiJiaDan":
                        Views.ShowSheHeBiJiaDan(params);
                        break;
                    case "/Project/ItemListView":
                        Views.ShowItesmListView(params);
                        break;
                    case "/Project/PlanProject":
                        Views.ShowProjectPlanView(params);
                        break;
                    case "/Contract/ProjectContracts":
                        Views.ShowProjectContracts(params);
                        break;
                    case "/Contract/ExampleContracts":
                        Views.ShowSampleContracts(params);
                        break;
                    case "/Project/ItemDetailView":
                        Views.ShowItemDetailView(params);
                        break;
					case "/FuKuanDan/Details":
					case "/FuKuanDan/Create":
                        Views.PrepareForFuKuanDan(params);
                        break;
                    default:
                        //default view
                        Views.ShowProjects();
                }
                HistoryManager.size++;
            },

            //HistoryManager
            //function:
            back: function () {
                if (HistoryManager.size <= 0) {
                    HistoryManager.load(GlobalResources.partialviewactions.assetsystem.url);
                } else {
                    HistoryManager.size--;
                    history.back();
                }
            },

            load: $.history.load
        };

        var Views = {
            ShowProjects: function (params) {
                var buttonContain = $("#button_command");

                //新建项目
                buttonContain.find(".newproject").click(function () {
                    Views.ShowNewProjectView();
                });

                //新建比价单
                buttonContain.find(".newbijiadan").click(function () {
                    Views.ShowNewBiJiaDanView();
                });

                //新建收入、支出单
                buttonContain.find(".newincome,.newexpend").click(function () {
                    var type = $(this).data('type');
                    Views.ShowAddIncomeOrExpend(type);
                });

                //项目计划
                buttonContain.find(".projectplan").click(function () {
                    Views.NavigateToProjectPlanView();
                });

                //项目合同
                buttonContain.find(".projectContract").click(function () {
                    Views.NavigateToPrjectContract();
                });

                //合同范本
                buttonContain.find(".contractSample").click(function () {
                    Views.NavigateToContractSample();
                });
				
				//付款单
                buttonContain.find(".fukuandan").click(function () {
                    Views.CreateFuKuanDan();
                });

                //修改密码
                buttonContain.find(".changepassword").click(function () {
                    Views.ShowChangePassword();
                });

                //make the project center
                $('#main').width(1200);

                //set up click event for project item
                CallBacks.SetUpProjectSelect();

            },

            ShowNewProjectView: function () {

                Views.ShowCommonFormView({
                    url: GlobalResources.partialviewactions.new_project_view.url,
                    onloadcomplete: function (container) {

                    }
                });
            },

            //弹出创建比价单的对话框
            ShowNewBiJiaDanView: function () {
                var id = Util.GetSelectedProjectId(),
                    querystring;

                if (!id) {
                    alert("请选择一个项目");
                    return;
                }
                querystring = $.query.set("ParentId", id).toString();

                Views.ShowCommonFormView({
                    url: GlobalResources.partialviewactions.new_bijiadan.url + querystring,
                    onloadcomplete: function (container) {
                    }
                });
            },

            //弹出修改密码对话框
            ShowChangePassword: function () {
                Views.ShowCommonFormView({
                    url: GlobalResources.partialviewactions.get_changepassword_view.url,
                    ajaxform: true,
                    onformcomplete: function (data) {
                        $.fancybox.close();
                        alert(data);
                    }
                });
            },

            //收入和支出
            ShowAddIncomeOrExpend: function (type) {
                var id = Util.GetSelectedProjectId(),
                    querystring;

                if (!id) {
                    alert("请选择一个项目");
                    return;
                }
                querystring = $.query.set("ParentId", id).set("type", type).toString();

                Views.ShowCommonFormView({
                    url: GlobalResources.partialviewactions.new_income_view.url + querystring,
                    ajaxform: true,
                    onformcomplete: function (data) {
                        alert(data.Description);
                    }
                });
            },

            NavigateToProjectPlanView: function () {
                var id = Util.GetSelectedProjectId(),
                    querystring;

                if (!id) {
                    alert("请选择一个项目");
                    return;
                }
                querystring = $.query.set("ParentId", id);
                window.location.href = GlobalResources.emptyactions.project_plan.url + querystring;
            },

            ///
            //项目计划页面
            ShowProjectPlanView: function (param) {
                var buttonContain = $("#button_command");

                //挂载新建计划事件
                buttonContain.find(".newplan").click(function () {
                    var datepicker = $("#new_plan_form").find("#FinishTime");
                    datepicker.datepicker();
                    datepicker[0].readOnly = true;

                    //打开添加项目计划窗口 
                    $("#new_plan_form").dialog("open");

                    //给添加项目计划窗口挂在AjaxForm，使之能够提交数据
                    Views.AjaxForm($("#new_plan_form"), {
                        onformcomplete: function (data) {
                            ProjectPlan.AddNewPlan(data);
                        }
                    })
                });

                //创建添加项目计划窗口
                $("#new_plan_form").dialog({
                    autoOpen: false,
                    title: "新建项目计划"
                });

                //挂载删除项目计划事件
                buttonContain.find(".deleteplan").click(function () {
                    ProjectPlan.DeleteSelectedPlan();
                });

                //挂载提交项目计划事件
                buttonContain.find(".submitplan").click(function () {
                    ProjectPlan.SubmitProjectPlan();
                });

                //项目计划相关的操作
                ProjectPlan.Initialize();

            },

            //打开项目合同列表
            NavigateToPrjectContract: function () {
                var id = Util.GetSelectedProjectId(),
                    querystring;

                if (!id) {
                    alert("请选择一个项目");
                    return;
                }
                querystring = $.query.set("ParentId", id);
                window.location.href = GlobalResources.emptyactions.project_contracts.url + querystring;
            },

            //显示项目相关的合同
            ShowProjectContracts: function (params) {
                ProjectContract.InitializeContractView(params);
            },

            //打开合同范本列表
            NavigateToContractSample: function () {
                window.location.href = GlobalResources.emptyactions.sample_contracts.url;
            },

            //显示合同范例管理页面
            ShowSampleContracts: function (params) {
                ProjectContract.InitializeContractView(params);
            },

			//创建付款单
			CreateFuKuanDan: function() {	
				var id = Util.GetSelectedProjectId(),
                    querystring;

                if (!id) {
                    alert("请选择一个项目");
                    return;
                }
                querystring = $.query.set("ParentId", id).toString();

				window.location.href = GlobalResources.emptyactions.create_fukuandan.url + querystring;
			},
			
			//为付款单的显示做些准备工作
			PrepareForFuKuanDan: function(params) {
				var currentStep = $("#CurrentStep").attr("value");
				var canOperateFuKuanDan = $("#canOperateFuKuanDan").attr("data-value");
				
				//let all edit box readonly
				$("#fukuanhost input").attr("readonly", "readonly");
				if (canOperateFuKuanDan == "False") return;
				
				
				//step is zero based, 0 is first step
				if (currentStep == "0" || currentStep == "1") {
					$("#fukuanhost input").removeAttr("readonly");
					
					//第一，二步，把第三四步编辑框，禁止掉
					$("#fukuanhost .third_step input").each(function () {
							$(this).attr("readonly", "readonly");
					});
					$("#fukuanhost .fourth_step input").each(function () {
							$(this).attr("readonly", "readonly");
					});
					
				} else if (currentStep == "2"){
					$("#fukuanhost .third_step input").each(function () {
							$(this).removeAttr("readonly");
					});
				} else if (currentStep == "3"){
					$("#fukuanhost .fourth_step input").each(function () {
							$(this).removeAttr("readonly");
					});
				}
			},
			
            //
            //创建比价单的页面
            CreateBiJiaDan: function () {
                /*if (!$('#bijiadan_container').length)
                return;

                var companyCount = $('#bijiadan_container').data('companycount'),
                width = companyCount * 200 + 6 * 100;
                $('#bijiadan_container').width(width);*/
                //为了让比价单table能居中，需要两个属性
                //1. 设置比较准确的wdith
                //2. margin: 0 auto;
                //BijiadanViews.SetBijiadanTableWidth();

                var buttonContain = $("#button_command");

                buttonContain.find(".uploadFile").click(function () {
                    Views.ShowUploadFileForBiJiaDan();
                });

                buttonContain.find(".newProduct").click(function () {
                    Views.ShowNewProduct();
                });

                buttonContain.find(".newSupplier").click(function () {
                    Views.ShowNewSupplier();
                });

                //autocomplete
                //ProductAutoCompleteUtils.ShowAvailableProducts();
                //SupplierAutoCompleteUtils.ShowAvailableSuppliers();

                BijiadanViews.BijiadanCommonSupport();
            },

            //
            //审核比价单
            ShowSheHeBiJiaDan: function (params) {
                var buttonContain = $("#button_command");
                buttonContain.find(".uploadFile").click(function () {
                    Views.ShowUploadFileForBiJiaDan();
                });

                BijiadanViews.BijiadanCommonSupport();
            },

            //
            //显示fancybox
            //options : onloadcomplete:当page加载完后调用
            //          onformcomplete:当是form时，等form submit成功后回调
            //          ajaxform: true表示是form，默认是false
            //
            ShowCommonFormView: function (options) {

                //if options.ajaxform is set, it will become an ajas form
                //that means the callback will return the data from server side.
                //otherwise it will just the container of the view

                $.fancybox({
                    width: 400,
                    type: 'ajax',
                    height: 'auto',
                    autoDimensions: false,
                    autoScale: false,
                    hideOnOverlayClick: false,
                    overlayShow: false,
                    padding: 2,
                    href: options.url,
                    onComplete: function (container) {
                        var container = $("#fancybox-wrap section.overlay_window");
                        //使用Ajax Form来上传数据
                        if (options.ajaxform) {
                            Views.AjaxForm(container, options)
                        }

                        if (options.onloadcomplete)
                            options.onloadcomplete(container);

                    }
                });
            },

            //
            //以 Ajax 方式上传数据
            AjaxForm: function (container, options) {
                var form = container.find("form");
                //使用Ajax PostForm
                form.ajaxForm({
                    dataType: 'json',
                    success: function (data) {
                        if (options.onformcomplete)
                            options.onformcomplete(data);
                    }
                });
            },

            //比价单文件上传页面
            ShowUploadFileForBiJiaDan: function () {
                var contain = $("#bijiadan_shenhe"),
                    id = contain.data("id"),
                    type = contain.data("type"),
                    querystring = $.query.set("type", type).set("ParentId", id).toString();

                Views.ShowCommonFormView({
                    url: GlobalResources.partialviewactions.upload_file_view.url + querystring,
                    onloadcomplete: function (container) {

                        //添加文件上传事件
                        container.find('#buttonUpload').click(function () {
                            Views.AjaxFileUpload(
                            {
                                reloadPage: false,
                                onSuccess: function (data, status) {
                                    //alert("succeed");
                                    Views.UpdateBiJiaDanAttachedFiles(id);
                                }
                            });
                        });
                    }
                });
            },

            //
            //更新比价单里面的附件文件
            //
            UpdateBiJiaDanAttachedFiles: function (id) {
                $.ajax({
                    url: GlobalResources.partialviewactions.get_attached_files.url,
                    type: GlobalResources.partialviewactions.get_attached_files.httpverb,
                    data: { Id: id },
                    success: function (data) {
                        //alert(data);
                        var parent = $("#bijiadan_attached_files");
                        parent.empty().append(data);
                    }
                });
            },

            //
            //文件上传
            AjaxFileUpload: function (options) {

                var dataholder = $("div.fileupload_body"),
                    id = dataholder.data('parentid'),
                    type = dataholder.data('type');

                $("#buttonUpload").ajaxStart(function () {
                    $(this).val('上传...').attr('disabled', true);
                }).ajaxComplete(function () {
                    $(this).val('上传成功').attr('disabled', false);
                }).ajaxSuccess(function (data) {
                    //alert(data);
                });


                $.ajaxFileUpload({
                    url: GlobalResources.emptyactions.file_upload.url,
                    secureuri: false,
                    fileElementId: 'fileToUpload',
                    dataType: 'json',
                    data: { parentId: id, type: type },
                    success: function (data, status) {
                        $.fancybox.close();

                        if (options.reloadPage) {
                            location.reload();
                        }

                        if (options.onSuccess)
                            options.onSuccess(data, status);
                        //                        if (typeof (data.error) != 'undefined') {
                        //                            if (data.error != '') {
                        //                                alert(data.error);
                        //                            } else {
                        //                                $.fancybox.close();
                        //                            }
                        //                        }
                    },
                    error: function (data, status, e) {
                        //alert(e);
                    }
                });

                return false;
            },

            //
            //新建商品信息
            ShowNewProduct: function () {

                Views.ShowCommonFormView({
                    url: GlobalResources.partialviewactions.new_product_view.url,
                    ajaxform: true,
                    onformcomplete: function (data) {
                        alert(data.Id); ;
                    }
                });
            },

            ShowNewSupplier: function () {
                Views.ShowCommonFormView({
                    url: GlobalResources.partialviewactions.new_supplier_view.url,
                    ajaxform: true,
                    onformcomplete: function (data) {
                        alert(data.Id); ;
                    }
                });
            },

            ShowItesmListView: function () {
                //make the project center
                $('#main').width(1200);

                ItemListViews.Initialize();
            },

            //
            //显示添加新计划页面
            ShowAddPlanView: function () {
                var parentId = $("#project_plan_view").data("projectid");

                querystring = $.query.set("ParentId", parentId).toString();

                Views.ShowCommonFormView({
                    url: GlobalResources.partialviewactions.add_project_plan_view.url + querystring,
                    ajaxform: true,
                    onformcomplete: function (data) {
                        ProjectPlan.AddNewPlan(data);
                    },
                    onloadcomplete: function (contain) {
                        var datepicker = contain.find("#FinishTime");
                        datepicker.datepicker();
                        datepicker[0].readOnly = true;
                    }
                });
            },

            //显示了收入支出，事件的详细试图
            ShowItemDetailView: function () {
                var buttonContain = $("#button_command");

                //项目计划
                buttonContain.find(".shenhe").click(function () {
                    Views.ShowShenHeCommentForm();
                });

                BijiadanViews.BijiadanCommonSupport();
            },

            ShowShenHeCommentForm: function () {
                var contain = $("fieldset"),
                    id = contain.data("id"),
                    type = contain.data("type"),
                    querystring = $.query.set("type", type).set("Id", id).toString();
                Views.ShowCommonFormView({
                    url: GlobalResources.partialviewactions.shenhe_comment_view.url + querystring,
                    ajaxform: true,
                    onformcomplete: function (data) {
                        window.close();
                    }
                });
            }


        };
        var BijiadanViews = {
            SetBijiadanTableWidth: function () {
                //计算表头的长度
                //set a tolerance
                var headerRowWidth = 1;
                $.each($(".header li"), function () {
                    headerRowWidth += $(this).outerWidth();
                })

                $("#bijiadan").width(headerRowWidth);
            },

            MonitorBaojiaChange: function () {
                $(".count, .price.baojia textarea").change(BijiadanViews.SetPrices);
            },

            MonitorShenhejiaChange: function () {
                $(".count, .price.shenhejia textarea").change(BijiadanViews.SetPrices);
            },

            MonitorReferencePriceChange: function () {
                $(".count, .price.referenceCompany textarea").change(BijiadanViews.SetPrices);
            },

            SetPrices: function () {
                //set total baojia
                $(".price.baojia.total").each(function (i) {
                    var totalbaojia = BijiadanViews.GetAllBaojia(i);
                    $(this).text(totalbaojia);
                });

                //set total shehejia
                $(".price.shenhejia.total").each(function (i) {
                    var totalshenhejia = BijiadanViews.GetAllShenhejia(i);
                    $(this).text(totalshenhejia);
                });
            },

            //supplierIndex is 0 based
            GetAllBaojia: function (supplierIndex) {
                return BijiadanViews.GetTotalPrice(supplierIndex, 0);
            },

            GetAllShenhejia: function (supplierIndex) {
                return BijiadanViews.GetTotalPrice(supplierIndex, 1);
            },

            //priceIndex 0 means baojia, 1 means shenhejia
            //
            GetTotalPrice: function (supplierIndex, priceIndex) {
                var totalPrice = 0;
                $("tr.productItem").each(function (i) {
                    var rowItem = $(this);
					//数量 cell index，zero based
					var countCellIndex = 3;
                    //xuhao, name, guige,count, unit
                    var productCellNumber = 5;
                    //baojia, shehejia
                    var priceCells = 2;

                    //no trim() function in javascript
                    var countValue = rowItem.find("td.count").find("textarea").val();//.trim();				
					//如果用户没有填，默认认为是1，除非显示填0
					if (countValue == "") 
						countValue = 1;
					
                    var priceCellNumber = productCellNumber + supplierIndex * priceCells + priceIndex;
                    var targetPriceCell = $(rowItem.find("td")[priceCellNumber]);
                    //单价//no trim() function in javascript
                    var baojia = targetPriceCell.find("textarea").val();//.trim();
					//产品价格=单价*数量
                    var productBaojia = parseFloat(baojia) * parseFloat(countValue);
                    if (!isNaN(productBaojia))
                        totalPrice += productBaojia;
                });

                //设置精度，小数点后三位
                return totalPrice.toFixed(3);
            },

            //设置bijiadan navigator的状态，高亮当前状态
            NavigatorUpdate: function () {
                $("#navigator span").removeClass("active");
                var status = $("#navigator #Status").attr("value");
                switch (status) {
                    case "ShengHeZhong":
                        $("#navigator #shenhezhong_stage").addClass("active");
                        break;
                    case "ShenHeWanCheng":
                        $("#navigator #shenhewancheng_stage").addClass("active");
                        break;
                    case "ZuoFei":
                        $("#navigator #zuofei_stage").addClass("active");
                        break;
                    case "GuiDang":
                        $("#navigator #guidang_stage").addClass("active");
                        break;
                    default:
                        $("#navigator #caogao_stage").addClass("active");
                }

            },

            //根据比价单当前状态，来觉得哪些选项不能编辑，哪些可以编辑
            UpdateEditableStatus: function () {
                var status = $("#navigator #Status").attr("value");
                switch (status) {
                    case "ShengHeZhong":
                        //selection control
                        $(".editable_caigou select").each(function () {
                            $(this).attr("disabled", "disabled");
                        });
                        //input control, don't use *disabled* here, orelse, the input value
                        //can't post to the web server.
                        $(".editable_caigou textarea, .baojia textarea").each(function () {
                            $(this).attr("readonly", "readonly");
                        });
                        break;
                    case "ShenHeWanCheng":
                    case "ZuoFei":
                        BijiadanViews.MakeBijiadanReadOnly();
                        break;
                    default: //草稿，所有选项都可以编辑
                        break;
                }
            },

            CheckBijiadanReadOnly: function () {
                if ($("#isReadOnly").text() == "True")
                    BijiadanViews.MakeBijiadanReadOnly();
            },

            MakeBijiadanReadOnly: function () {
                $("#bijiadan_edit_area").find("input, select, textarea, button").each(function () {
                    $(this).attr("disabled", "disabled");
                });

                BijiadanViews.HideShenheContainer();

                //View的时候允许查看附件
                //BijiadanViews.HideAttachedFilesContainer();
            },

            HideShenheContainer: function () {
                $("#shenhe").hide();
            },

            HideAttachedFilesContainer: function () {
                $("#bijiadan_attached_files").hide();
            },

            //
            BijiadanCommonSupport: function () {
                //为了让比价单table能居中，需要两个属性
                //1. 设置比较准确的wdith
                //2. margin: 0 auto;
                //BijiadanViews.SetBijiadanTableWidth();

                //set and monitor prices
                BijiadanViews.SetPrices();
                BijiadanViews.MonitorBaojiaChange();
                BijiadanViews.MonitorShenhejiaChange();
                BijiadanViews.MonitorReferencePriceChange();

                //update Navigator accordingly
                BijiadanViews.NavigatorUpdate();

                //根据比价单的状态设置哪些可以编辑
                BijiadanViews.UpdateEditableStatus();

                //检测用户是否有权限操作
                BijiadanViews.CheckBijiadanReadOnly();
				
				//reference http://labs.ft.com/2009/05/auto-growing-textareas/
				$("textarea").each(function(){
					  var ta = this;
					  var maxrows = 30;
					  var lh = ta.clientHeight / ta.rows;
					  while (ta.scrollHeight > ta.clientHeight && !window.opera && ta.rows < maxrows) {
						ta.style.overflow = 'hidden';
						ta.rows += 1;
					  }
					  if (ta.scrollHeight > ta.clientHeight) ta.style.overflow = 'auto';
				})
            }
        };

        var ProductAutoCompleteUtils = {

            ShowAvailableProducts: function () {
                ProductAutoCompleteUtils.GetAllProducts();

                //add new avaiable product
                $(".name input").blur(function () {
                    var value = this.value;
                    ProductAutoCompleteUtils.AddProduct(value);
                });

                ProductAutoCompleteUtils.SetUnit();
            },

            GetAllProducts: function () {
                $.ajax({
                    url: GlobalResources.jsonactions.get_all_products.url,
                    type: GlobalResources.jsonactions.get_all_products.httpverb,
                    success: function (data) {
                        ProductAutoCompleteUtils.availableProducts = data;

                        //set up product source
                        ProductAutoCompleteUtils.SetProductAutoCompleteSource();
                    }
                });

            },

            SetProductAutoCompleteSource: function () {
                $(".name input").autocomplete({
                    source: ProductAutoCompleteUtils.availableProducts
                });
            },

            AddProduct: function (product) {
                var isExist = false;
                $.each(ProductAutoCompleteUtils.availableProducts, function () {
                    if (this == product) isExist = true;
                })

                if (isExist) return;

                ProductAutoCompleteUtils.availableProducts.push(product);

                //set up product source
                ProductAutoCompleteUtils.SetProductAutoCompleteSource();

                //add new avaiable product
                $(".name input").blur(function () {
                    var value = this.value;
                    ProductAutoCompleteUtils.AddProduct(value);
                });
            },

            SetProductAutoCompleteSource: function () {
                $(".name input").autocomplete({
                    source: ProductAutoCompleteUtils.availableProducts
                });
            },

            //set unit value base on the auto compelete selection
            SetUnit: function () {
                $(".name input").bind("autocompleteselect", function (e, ui) {
                    //alert(ui.item.value);
                    var productNameInputElement = e.currentTarget;
                    var unitInputElement = $(productNameInputElement).parent().siblings(".unit").find("input");

                    var selectProductName = ui.item.value;
                    ProductAutoCompleteUtils.GetProductUnit(selectProductName, unitInputElement);
                });
            },

            //get unit by ajax, and set the unit value to the corresponding html element
            GetProductUnit: function (name, unitInputElement) {
                $.ajax({
                    url: GlobalResources.jsonactions.get_product_unit.url,
                    type: GlobalResources.jsonactions.get_product_unit.httpverb,
                    data: { productName: name },
                    success: function (data) {
                        ProductAutoCompleteUtils.productUnit = data;
                        unitInputElement.val(ProductAutoCompleteUtils.productUnit);
                    }
                });
            }
        };

        var SupplierAutoCompleteUtils = {

            ShowAvailableSuppliers: function () {
                SupplierAutoCompleteUtils.GetAllSuppliers();

                //add new avaiable supplier
                $(".companyName input").blur(function () {
                    var value = this.value;
                    SupplierAutoCompleteUtils.AddSupplier(value);
                });

                SupplierAutoCompleteUtils.SetContactInfo();
            },

            GetAllSuppliers: function () {
                $.ajax({
                    url: GlobalResources.jsonactions.get_all_suppliers.url,
                    type: GlobalResources.jsonactions.get_all_suppliers.httpverb,
                    success: function (data) {
                        SupplierAutoCompleteUtils.availableSuppliers = data;

                        //set up supplier source
                        SupplierAutoCompleteUtils.SetsupplierAutoCompleteSource();
                    }
                });

            },

            SetsupplierAutoCompleteSource: function () {
                $(".companyName input").autocomplete({
                    source: SupplierAutoCompleteUtils.availableSuppliers
                });
            },

            AddSupplier: function (supplier) {
                var isExist = false;
                $.each(SupplierAutoCompleteUtils.availableSuppliers, function () {
                    if (this == supplier) isExist = true;
                })

                if (isExist) return;

                SupplierAutoCompleteUtils.availableSuppliers.push(supplier);

                //set up supplier source
                SupplierAutoCompleteUtils.SetsupplierAutoCompleteSource();

                //add new avaiable supplier
                $(".companyName input").blur(function () {
                    var value = this.value;
                    SupplierAutoCompleteUtils.Addsupplier(value);
                });
            },

            SetsupplierAutoCompleteSource: function () {
                $(".companyName input").autocomplete({
                    source: SupplierAutoCompleteUtils.availableSuppliers
                });
            },

            SetContactInfo: function () {
                $(".companyName input").bind("autocompleteselect", function (e, ui) {
                    //alert(ui.item.value);	
                    var supplierNameInputElement = e.currentTarget;
                    var companeIndex = $(supplierNameInputElement).parent().parent().attr("data-supplierindex");

                    var selectSupplierName = ui.item.value;
                    SupplierAutoCompleteUtils.GetSupplier(selectSupplierName, companeIndex);
                });
            },

            //get supplier information by ajax, and set the information value to the corresponding html element
            GetSupplier: function (name, companyIndex) {
                $.ajax({
                    url: GlobalResources.jsonactions.get_supplier.url,
                    type: GlobalResources.jsonactions.get_supplier.httpverb,
                    data: { supplierName: name },
                    success: function (data) {
                        //设置联系人
                        var contacterElement = $(".Contacter").find("li[data-supplierindex='" + companyIndex + "'] input");
                        contacterElement.val(data.Contacter);

                        //设置电话
                        var callNumberElement = $(".CallNumber").find("li[data-supplierindex='" + companyIndex + "'] input")
                        callNumberElement.val(data.CallNumber);
                    }
                });
            }
        };


        var CallBacks = {

            SetUpProjectSelect: function () {

                $(".project_item_body").click(function () {

                    $('.project_item_body').removeClass('selected');
                    $(this).addClass('selected');
                });
            }
        };

        var Util = {

            //获得选择项目的id
            GetSelectedProjectId: function () {
                var selectedProject = $('div.project_item_body.selected');

                if (!selectedProject.length)
                    return null;

                return selectedProject.data('id');
            }
        };

        var ProjectPlan = {

            Initialize: function () {
                //给所有的项目添加tooltip来显示详细信息
                ProjectPlan.AddToolTipSupport();

                //添加item的select事件支持
                ProjectPlan.AddSelectEventSupport();
            },

            GetFormatedDate: function (cshapDate) {
                var beginIndex = cshapDate.indexOf("("),
                    endIndex = cshapDate.indexOf(")"),
                    datastring = cshapDate.substring(beginIndex + 1, endIndex),
                    retDate = new Date(0);
                retDate.setUTCDate(datastring);

                return retDate.getYear() + "-" + retDate.getMonth() + "-" + retDate.getDay();
            },
            AddNewPlan: function (newPlan) {
                var destRow;

                ProjectPlan.MakeSureDateTimeRowExisted(newPlan.FinishTimeString);

                destRow = $("#project_plan_view tr[data-itemdate='" + newPlan.FinishTimeString + "']");

                switch (newPlan.type) {
                    case 1: //收入SupportTypes.Income
                        destRow.find("div.incomeitems").append(ProjectPlan.GetPlaneItemSpan(newPlan));
                        break;
                    case 2: //支出SupportTypes.Expend
                        destRow.find("div.expenditems").append(ProjectPlan.GetPlaneItemSpan(newPlan));
                        break;
                    case 3: //事件SupportTypes.Event
                        destRow.find("div.eventitems").append(ProjectPlan.GetPlaneItemSpan(newPlan));
                        break;
                }

                ProjectPlan.AddToolTipSupport();
                //添加item的select事件支持
                ProjectPlan.AddSelectEventSupport();
            },

            MakeSureDateTimeRowExisted: function (dateTime) {
                var rows = $("#project_plan_view tr"),
                    tablebody = $("#project_plan_view table tbody"),
                    dateinput = new Date(dateTime),
                    existed = false,
                    elementPosition,
                    newrow;

                rows.each(function (index, element) {
                    var daterow = new Date($(element).data('itemdate'));
                    if (daterow.valueOf() == dateinput.valueOf()) {
                        existed = true;
                        return false;
                    }
                    if (daterow.valueOf() > dateinput.valueOf()) {
                        elementPosition = $(element);
                        return false;
                    }
                });

                if (existed) return;

                newrow = "<tr data-itemdate = '" + dateTime + "'>"
                            + "<td class='plan_item_data'><span>" + dateTime + "</span></td>"
                            + "<td> <div class='incomeitems'></div></td>"
                            + "<td> <div class='expenditems'></div></td>"
                            + "<td> <div class='eventitems'></div></td>"
                            + "</tr>";
                if (elementPosition)
                    elementPosition.before(newrow);
                else
                    tablebody.append(newrow);
            },

            GetPlaneItemSpan: function (newPlan) {
                var items = "<span ";

                switch (newPlan.type) {
                    case 1: //收入SupportTypes.Income
                        items = items + " class = 'item item_income item_plan' ";
                        break;
                    case 2: //支出SupportTypes.Expend
                        items = items + " class = 'item item_expend item_plan' ";
                        break;
                    case 3: //事件SupportTypes.Event
                        items = items + " class = 'item item_event item_plan' ";
                        break;
                };

                items = items + " data-id = '" + newPlan.Id + "'"
                                + " data-comment = '" + newPlan.Comment + "'"
                                + ">" + newPlan.Name + "</span>";
                return items;

            },

            //
            //对项目计划里面的相添加tooltip支持，使之能显示item的描述
            //
            AddToolTipSupport: function () {

                $("#project_plan_view span.item").tooltip({
                    delay: 1,
                    showURL: false,
                    bodyHandler: function () {
                        var comment = $(this).data("comment");
                        return "<div id='project_plan_tooltop'>" + "<div class='tooltip_comment'>" + comment + "</div></div>";
                    }
                });

            },

            AddSelectEventSupport: function () {
                $("#project_plan_view span.item").click(function () {
                    $("#project_plan_view span.item").removeClass('select');
                    $(this).addClass('select');
                });
            },

            //
            //删除选择的项目计划项
            //
            DeleteSelectedPlan: function () {
                var selectedPlan = $("#project_plan_view span.item.select"),
                    planId;
                if (!selectedPlan)
                    alert("请选择一个项目计划");
                if (!selectedPlan.hasClass("item_plan")) {
                    alert("非计划的项目项不允许删除");
                    return;
                }


                planId = selectedPlan.data("id");

                $.ajax({
                    url: GlobalResources.jsonactions.delete_project_plan_item.url,
                    type: GlobalResources.jsonactions.delete_project_plan_item.httpverb,
                    data: { planId: planId },
                    success: function (data) {
                        $("#project_plan_view span.item.select").remove();
                    }
                });

            },

            //
            //提交整个项目的计划
            //
            SubmitProjectPlan: function () {
                var projectid = $("#project_plan_view").data("projectid");

                $.ajax({
                    url: GlobalResources.jsonactions.submit_project_plan.url,
                    type: GlobalResources.jsonactions.submit_project_plan.httpverb,
                    data: { ParentId: projectid },
                    success: function (data) {

                    }
                });
            }



        };

        //项目合同管理相关类
        var ProjectContract = {

            InitializeContractView: function () {

                //注册合同行选择事件
                $(".contact_item").click(ProjectContract.Contact_item_Selcted);

                $(".uploadContract").click(ProjectContract.Upload_Contract);

                $(".deleteContract").click(ProjectContract.Delete_Contract);
            },

            Contact_item_Selcted: function (event) {
                $(".contact_item").removeClass("select");
                $(this).addClass("select");
            },

            Upload_Contract: function () {
                var contain = $("#contacts_view"),
                    id = contain.data("id"),
                    type = contain.data("type"),
                    querystring = $.query.set("type", type).set("ParentId", id).toString();
                Views.ShowCommonFormView({
                    url: GlobalResources.partialviewactions.upload_file_view.url + querystring,
                    onloadcomplete: function (container) {

                        //添加文件上传事件
                        container.find('#buttonUpload').click(function () {
                            Views.AjaxFileUpload(
                            {
                                reloadPage: true,
                                onSuccess: ProjectContract.Upload_Contract_Success
                            });
                        });
                    }
                });
            },

            Upload_Contract_Success: function (data, status) {
                alert(status);
            },

            Delete_Contract: function () {

            }

        };

        //项目 比价单，收入单，支出单列表页面相关操作
        var ItemListViews = {

            Initialize: function () {
                var mainContain = $("#listitem_main_body"),
                    filterContain = $("#listitem_filters"),
                    bodyContain = $("#listitem_body");

                filterContain.find("input:checkbox").click(ItemListViews.FilterHandler);
            },

            //当点击列表上面的选择按钮是执行下面的操作
            FilterHandler: function () {
                var isTypeFilter = $(this).parent().hasClass("listitem_type_checkbox"),
                        isChecked = $(this).is(":checked"),
                        checkedValue = $(this).val(),
                        select;
                if (isTypeFilter) {
                    $("#listitem_body tbody tr[data-type = '" + checkedValue + "']").toggleClass("typehidden");
                } else {
                    $("#listitem_body tbody tr[data-status = '" + checkedValue + "']").toggleClass("statushidden");
                };
            }

        };

        return {
            init: function () {
                HistoryManager.init();
            }
        }
    })(window.jQuery);
}).call(window);

jQuery(document).ready(BlackBirdApp.init);